package com.app.backend.base.serviceImpl;

import com.app.backend.base.dao.UserDao;
import com.app.backend.base.dao.mapper.PermissionMapper;
import com.app.backend.base.dao.mapper.UserRoleMapper;
import com.app.backend.base.entity.Permission;
import com.app.backend.base.entity.Role;
import com.app.backend.base.entity.User;
import com.app.backend.base.service.UserService;
import com.app.backend.base.vo.UserVo;
import com.app.backend.common.base.BaseDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.List;

/**
 * @program: UserServiceImpl
 * @description:
 * @author: Zhun.Xiao
 * @create: 2020-02-08 18:05
 **/

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {


    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserDao userDao;

    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        List<Role> roleList = userRoleMapper.findByUserId(user.getId());
        user.setRoles(roleList);
        List<Permission> permissionsList = permissionMapper.findByUserId(user.getId());
        user.setPermissions(permissionsList);
        return user;
    }

    @Override
    public Page<User> findAllByConditionPage(UserVo userVo, Pageable initPage) {
        return userDao.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                //  Join<User,Role> roleJoin = root.join("")

                Path<String> username = root.get("username");
                Path<String> mobile = root.get("mobile");

                //todo 关联表查询

                return null;
            }
        }, initPage);
    }


    @Override
    public BaseDao<User, String> getRepository() {
        return userDao;
    }
}